package com.tchy.cloud.tools;

import java.io.File;

/**
 * Created by angus584 on 2015/3/24.
 */
public class FileUtil {
    /**
     * 创建文件,如果文件名重复则自动更改文件名
     *
     * @param path     文件路径
     * @param fileName 文件名
     * @param count    默认传入初始次数 2
     * @return 返回新创建的文件
     * @throws Exception
     */
    public static File getFileByOriginalFileName(String path, String fileName, int count) throws Exception {

        File targetFile = new File(path, fileName);


        if (!targetFile.exists()) {
            targetFile.mkdirs();
        } else {


            String new_fileName = fileName.substring(0, fileName.lastIndexOf("."));

            if (count != 2) {

                new_fileName = fileName.substring(0, fileName.lastIndexOf("(" + (count - 1) + ")"));


            }

            new_fileName += "(" + count + ")";

            //加入文件后缀
            if (fileName != null && !"".equals(fileName) && fileName.lastIndexOf(".") != -1) {

                new_fileName += fileName.substring(fileName.lastIndexOf("."), fileName.length()).toLowerCase();

            }

            count++;
            //递归，调用自身
            targetFile = getFileByOriginalFileName(path, new_fileName, count);


        }

        return targetFile;

    }
}
